#include "dbwrapper.h"

DBWrapper::DBWrapper(const DBOptions& opt, std::string path) noexcept
    : db_path_(path) {
  this->db_.reset(this->Open(opt));
}

DBWrapper::DBWrapper(DBWrapper&& other) noexcept
    : db_(std::move(other.db_)), db_path_(std::move(other.db_path_)) {}

DBWrapper& DBWrapper::operator=(DBWrapper&& rhs) noexcept {
  if (this != &rhs) {
    db_ = std::move(rhs.db_);
    db_path_ = std::move(rhs.db_path_);
  }
  return *this;
}

bool DBWrapper::isValid() { return this->db_ == nullptr; }

bool DBWrapper::Put(const std::string& key, const std::string& value) {
  auto status = this->db_->Put(leveldb::WriteOptions(), key, value);
  return status.ok();
}

std::string DBWrapper::Get(const std::string& key) {
  std::string value;
  auto status = this->db_->Get(leveldb::ReadOptions(), key, &value);
  return value;
}

bool DBWrapper::Del(const std::string& key) {
  auto status = this->db_->Delete(leveldb::WriteOptions(), key);
  return status.ok();
}

DBIterator DBWrapper::Iterator() {
  auto it_ = this->db_->NewIterator(leveldb::ReadOptions());
  return DBIterator(it_);
}

leveldb::DB* DBWrapper::Open(const DBOptions& opt) {
  leveldb::DB* db_p;
  leveldb::Options options;
  options.create_if_missing = opt.create_if_missing;
  auto status = leveldb::DB::Open(options, db_path_, &db_p);
  if (!status.ok()) {
    delete db_p;
    db_p = nullptr;
  }
  return db_p;
}
